package com.chaobl.user.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chaobl.user.user.dto.AjaxResult;
import com.chaobl.user.user.dto.Jscode2session;
import com.chaobl.user.user.entity.XcxUser;
import com.chaobl.user.user.service.IXcxUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 小程序用户主表 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-04-14
 */
@RestController
@RequestMapping("/user/xcx-user")
public class XcxUserController {
    @Value("${weixin.appId}")
    String _appId = "";

    @Value("${weixin.secret}")
    String _secret = "";

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    IXcxUserService xcxUserService;

    // 通过微信登录code获取openid，在用openid查用户表。返回用户对象
    @GetMapping("/getUserByWxLoginCode")
    public Object getUserByWxLoginCode(String code, Integer enterpriseId, Integer shopId) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(false);

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + _appId + "&secret=" + _secret + "&js_code=" + code + "&grant_type=authorization_code";
        Jscode2session jscode2session = restTemplate.getForObject(url, Jscode2session.class);

        XcxUser xcxUser = new XcxUser();

        if (jscode2session.getOpenid() != null) {
            List<XcxUser> list = xcxUserService.list(new QueryWrapper<XcxUser>().eq("openId", jscode2session.getOpenid()));
            if (list != null && list.size() > 0) {
                ajaxResult.setSuccess(true);
                ajaxResult.setData(list.get(0));
                return ajaxResult;

            } else {
                xcxUser.setEnterpriseId(enterpriseId);
                xcxUser.setShopId(shopId);
                xcxUser.setOpenId(jscode2session.getOpenid());
                xcxUser.setCreateTime(LocalDateTime.now());
                xcxUser.setUpdateTime(LocalDateTime.now());

                if(xcxUserService.save(xcxUser)) {
                    ajaxResult.setSuccess(true);
                    ajaxResult.setData(xcxUser);
                }
            }

        } else
            ajaxResult.setErrorMsg(jscode2session.getErrmsg());

        return ajaxResult;
    }
}
